package com.controller;

import java.util.Arrays;
import java.util.Date;


import com.alibaba.fastjson.JSONObject;
import com.constant.AuthConstant;
import com.service.ChongdianzhuangbaoxiuService;
import com.utils.RedisClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.domain.entity.WeixiuhuifuEntity;

import com.service.WeixiuhuifuService;
import com.utils.PageUtils;
import com.utils.R;


@RestController
@RequestMapping("/weixiuhuifu")
public class WeixiuhuifuController {
    @Autowired
    private WeixiuhuifuService weixiuhuifuService;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private ChongdianzhuangbaoxiuService chongdianzhuangbaoxiuService;

    /**
     * 分页查询维修恢复表
     */
    @GetMapping("/page")
    public R page(@RequestParam int pageNum, @RequestParam int pageSize, WeixiuhuifuEntity weixiuhuifu) {

        PageUtils page = weixiuhuifuService.queryPage(pageNum, pageSize, weixiuhuifu);

        return R.ok().put("data", page);
    }

    /**
     * 维修恢复详情接口
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {

        //先查询redis
        String RJson = redisClient.getString(AuthConstant.RESTORED_INFO_PREFIX + id);
        if (StringUtils.isNotEmpty(RJson)) {
            WeixiuhuifuEntity entity = JSONObject.parseObject(RJson, WeixiuhuifuEntity.class);
            return R.ok().put("data", entity);
        }

        WeixiuhuifuEntity entity = weixiuhuifuService.selectById(id);

        if (entity != null) {
            redisClient.setMinString(AuthConstant.RESTORED_INFO_PREFIX + id, JSONObject.toJSONString(entity), 1200L);
        }

        return R.ok().put("data", entity);
    }

    /**
     * 维修恢复详情修改
     */
    @PostMapping("/update")
    public R update(@RequestBody WeixiuhuifuEntity weixiuhuifu) {

        weixiuhuifuService.updateById(weixiuhuifu);
        return R.ok("修改成功");
    }

    /**
     * 维修恢复详情删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        weixiuhuifuService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 报修提交维修恢复
     */
    @PostMapping("/save")
    public R save(@RequestBody WeixiuhuifuEntity weixiuhuifu) {
        weixiuhuifu.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());

        weixiuhuifuService.insert(weixiuhuifu);
        chongdianzhuangbaoxiuService.deleteByBianHao(weixiuhuifu.getDianzhuangbianhao());

        return R.ok();
    }


}
